package com.atlin.project.controller;

import com.atlin.project.annotation.AuthCheck;
import com.atlin.project.common.BaseResponse;
import com.atlin.project.common.DeleteRequest;
import com.atlin.project.common.ErrorCode;
import com.atlin.project.common.ResultUtils;
import com.atlin.project.contant.UserConstant;
import com.atlin.project.exception.BusinessException;
import com.atlin.project.exception.ThrowUtils;
import com.atlin.project.model.domain.BiProducts;
import com.atlin.project.model.domain.ServiceUsage;
import com.atlin.project.model.domain.SysUser;
import com.atlin.project.model.dto.biProduces.BiProductsAddRequest;
import com.atlin.project.model.dto.biProduces.BiProductsQueryRequest;
import com.atlin.project.model.dto.biProduces.BiProductsUpdateRequest;
import com.atlin.project.model.dto.biProduces.PlaceAnOrderRequest;
import com.atlin.project.model.enums.biProduces.BiProductsStatusEnum;
import com.atlin.project.model.vo.biProduces.BiProductsVO;
import com.atlin.project.model.vo.serviceUsage.ServiceUsageVO;
import com.atlin.project.service.BiProductsOrderService;
import com.atlin.project.service.BiProductsService;
import com.atlin.project.service.ServiceUsageService;
import com.atlin.project.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 模版接口
 *
 * @author atlin
 */
@RestController
@RequestMapping("/biProducts")
public class BiProductsController {

    @Resource
    private BiProductsService biProductsService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private BiProductsOrderService biProductsOrderService;

    @Resource
    private ServiceUsageService serviceUsageService;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param biProductsAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addBiProducts(@RequestBody BiProductsAddRequest biProductsAddRequest, HttpServletRequest request) {
        if (biProductsAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Integer status = biProductsAddRequest.getStatus();
        BiProductsStatusEnum enumByValue = BiProductsStatusEnum.getEnumByValue(status);
        ThrowUtils.throwIf(enumByValue == null, ErrorCode.PARAMS_ERROR, "不支持的状态");

        BiProducts biProducts = new BiProducts();
        BeanUtils.copyProperties(biProductsAddRequest, biProducts);

        biProductsService.valid(biProducts, true);


        boolean result = biProductsService.save(biProducts);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newBiProductsId = biProducts.getId();
        return ResultUtils.success(newBiProductsId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteBiProducts(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        BiProducts oldbiProducts = biProductsService.getById(id);
        ThrowUtils.throwIf(oldbiProducts == null, ErrorCode.NULL_ERROR);

        boolean b = biProductsService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param biProductsUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateBiProducts(@RequestBody BiProductsUpdateRequest biProductsUpdateRequest) {
        if (biProductsUpdateRequest == null || biProductsUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Integer status = biProductsUpdateRequest.getStatus();
        BiProductsStatusEnum enumByValue = BiProductsStatusEnum.getEnumByValue(status);
        ThrowUtils.throwIf(enumByValue == null, ErrorCode.PARAMS_ERROR, "不支持的状态");

        BiProducts biProducts = new BiProducts();
        BeanUtils.copyProperties(biProductsUpdateRequest, biProducts);

        // 参数校验
        biProductsService.valid(biProducts, false);
        long id = biProductsUpdateRequest.getId();
        // 判断是否存在
        BiProducts oldbiProducts = biProductsService.getById(id);
        ThrowUtils.throwIf(oldbiProducts == null, ErrorCode.NULL_ERROR);


        boolean result = biProductsService.updateById(biProducts);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<BiProducts> getBiProductsById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        BiProducts biProducts = biProductsService.getById(id);
        if (biProducts == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        return ResultUtils.success(biProducts);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<BiProductsVO> getBiProductsVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        BiProducts biProducts = biProductsService.getById(id);
        if (biProducts == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        BiProductsVO biProductsVO = BiProductsVO.objToVo(biProducts);
        return ResultUtils.success(biProductsVO);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param biProductsQueryRequest 查询参数
     * @param request                查询请求
     * @return 分页封装类
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<BiProductsVO>> listBiProductsVOByPage(@RequestBody BiProductsQueryRequest biProductsQueryRequest,
                                                                   HttpServletRequest request) {
        long current = biProductsQueryRequest.getCurrent();
        long size = biProductsQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<BiProducts> biProductsPage = biProductsService.page(new Page<>(current, size),
                biProductsService.getQueryWrapper(biProductsQueryRequest));

        Page<BiProductsVO> biProductsVOPage = biProductsService.getBiProductsVOPage(biProductsPage, request);

        return ResultUtils.success(biProductsVOPage);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param biProductsQueryRequest 查询参数
     * @param request                查询请求
     * @return 分页
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<BiProducts>> listBiProductsByPage(@RequestBody BiProductsQueryRequest biProductsQueryRequest,
                                                               HttpServletRequest request) {
        long current = biProductsQueryRequest.getCurrent();
        long size = biProductsQueryRequest.getPageSize();
        Page<BiProducts> biProductsPage = biProductsService.page(new Page<>(current, size),
                biProductsService.getQueryWrapper(biProductsQueryRequest));
        return ResultUtils.success(biProductsPage);
    }

    // endregion

    /**
     * 下单
     *
     * @param placeAnOrderRequest
     * @param request
     * @return
     */
    @PostMapping("/placeAnOrder")
    public String placeAnOrder(@RequestBody PlaceAnOrderRequest placeAnOrderRequest,
                               HttpServletRequest request) {

        if (placeAnOrderRequest == null || placeAnOrderRequest.getProductsId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "产品不存在");
        }

        SysUser loginUser = sysUserService.getLoginUser(request);

        return biProductsOrderService.placeAnOrder(placeAnOrderRequest.getProductsId(), loginUser);
    }

    /**
     * 获取我的服务使用信息
     *
     * @param request
     * @return
     */
    @GetMapping("/get/service/usages")
    public BaseResponse<ServiceUsage> getMyBiProductsServiceUsages(HttpServletRequest request) {
        SysUser loginUser = sysUserService.getLoginUser(request);
        ServiceUsage serviceUsage = serviceUsageService.getServiceUsageByUserId(loginUser.getId());
        return ResultUtils.success(serviceUsage);
    }

}
